package com.yy.device.boot.handler;

import com.yy.device.boot.DeviceDataContainer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 超时处理程序
 * TimeOutHandler
 *
 * @author sunzhiqiang
 * @date 2021/12/14 14:28:37
 */
@Slf4j
public class TimeOutHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("链接断开。。。");
        DeviceDataContainer.unRegister(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        Channel channel = ctx.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        String ip = socketAddress.getHostString();
        int port = socketAddress.getPort();
        log.info("connection success,ctx:{}", ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                try {
                    log.info("userEventTriggered:{}", state);
                    DeviceDataContainer.unRegister(ctx);
                } finally {
                    ctx.close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 处理细节交给实现类disconnect方法处理，完成后关闭ctx
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        try {
            log.info("链接断开。。。");
            DeviceDataContainer.unRegister(ctx);
        } finally {
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        DeviceDataContainer.unRegister(ctx);
        ctx.close();
    }
}
